package codeGen.core;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class FreemarkerUtil {
    private static Configuration conf;

    static {
        try {
            conf = new Configuration();
            //设置模版目录
            String templatesPath = BeanUtil.class.getClassLoader().getResource("").getPath() + "templates";
            conf.setDirectoryForTemplateLoading(new File(templatesPath));
            conf.setObjectWrapper(new DefaultObjectWrapper());
            conf.setDefaultEncoding("UTF-8");
            conf.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void genResource(String template, OutputStream os, Object data) {
        try {
            Template temp = conf.getTemplate(template);
            temp.process(data, new OutputStreamWriter(os));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
